package com.alibaba.citrus.cr.sales.plan.facade.service.salesplan.report;

import com.alibaba.citrus.cr.common.annotation.FacadeInvoker;
import com.alibaba.citrus.cr.common.exception.FacadeException;
import com.alibaba.citrus.cr.sales.plan.dto.api.response.SalesPlanAuditRecordResponse;
import com.alibaba.citrus.cr.sales.plan.facade.service.salesplan.audit.AuditSettingDetailServiceImpl;
import com.alibaba.citrus.cr.sales.plan.model.SalesPlanReportAuditStatusEnum;
import com.alibaba.citrus.cr.sales.plan.model.enums.*;
import com.alibaba.citrus.cr.sales.plan.repository.PlatformEnhanceRepository;
import com.alibaba.citrus.cr.sales.plan.repository.SalesPlanAuditRepository;
import com.alibaba.citrus.cr.sales.plan.repository.SalesPlanAuditTaskRepository;
import com.alibaba.citrus.cr.sales.plan.repository.SalesPlanReportRepository;
import com.alibaba.citrus.cr.sales.plan.repository.request.OrganizationListQueryRequest;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanAuditSDO;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanAuditTaskSDO;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanReportSDO;
import com.alibaba.citrus.cr.sales.plan.api.salesplan.report.SalesPlanReportQueryService;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.QuerySalesPlanAuditRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.QuerySalesPlanReportRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.SalesPlanAuditTaskQueryRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.SalesPlanReportPageQueryRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.SalesPlanReportQueryRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.SalesPlanReportRequest;
import com.alibaba.cz.base.tool.Nullable;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.message.ErrorMessage;
import com.alibaba.cz.base.tool.page.PageResult;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.auditsetting.model.AuditSetting;
import com.epoch.app.bcorder.auditsetting.service.AuditSettingService;
import com.epoch.app.bcorder.auditsettingdetail.model.AuditSettingDetail;
import com.epoch.app.bcorder.auditsettingdetail.service.AuditSettingDetailService;
import com.epoch.app.bcorder.contants.BcOrderConstants;
import com.epoch.app.bcorder.model.dto.*;
import com.epoch.app.bcorder.model.enums.AuditSettingStatusEnum;
import com.epoch.app.bcorder.model.enums.AuditSettingTypeEnum;
import com.epoch.app.bcorder.sales_plan.salesplanreport.model.SalesPlanReport;
import com.epoch.app.bcorder.sales_plan.salesplanreport.service.SalesPlanReportService;
import com.epoch.app.bcorder.service.BcOrderService;
import com.epoch.app.crplatformenhance.enums.OrganizationTypeEnum;
import com.epoch.app.crplatformenhance.enums.RoleCodeEnum;
import com.epoch.app.crplatformenhance.sdo.EmployeeSDO;
import com.epoch.app.crplatformenhance.sdo.OrganizationSDO;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class SalesPlanReportQueryServiceImpl implements SalesPlanReportQueryService {

    private final Log log = Log.getLogger(SalesPlanReportQueryServiceImpl.class);
    @Resource
    private SalesPlanReportRepository salesPlanReportRepository;

    @Resource
    private SalesPlanAuditTaskRepository salesPlanAuditTaskRepository;

    @Resource
    private SalesPlanAuditRepository salesPlanAuditRepository;

    @Resource
    private PlatformEnhanceRepository platformEnhanceRepository;

    @Resource(name = "auditSettingServiceImpl")
    private AuditSettingService auditSettingService;

    @Resource(name = "auditSettingDetailServiceImpl")
    private AuditSettingDetailService auditSettingDetailService;

    @Resource
    private BcOrderService bcOrderService;

    @Resource
    private SalesPlanReportService salesPlanReportService;

    private final static String USER_PREFIX = "CZ_";

    private final static String SALES_PLAN_REPORT_SWITCH = "TRUE";

    @Override
    @FacadeInvoker
    public Result<PageResult<List<SalesPlanReportSDO>>> pageQuerySalesPlanReport(SalesPlanReportPageQueryRequest request) {
        return Result.success(salesPlanReportRepository.pageQuery(request));
    }

    @Override
    @FacadeInvoker
    public Result<SalesPlanReportSDO> querySalesPlanReport(SalesPlanReportQueryRequest request) {
        SalesPlanReportPageQueryRequest pageQueryRequest = convertSalesPlanReportPageQueryRequest(request);
        pageQueryRequest.setStart(0);
        pageQueryRequest.setLimit(1);
        PageResult<List<SalesPlanReportSDO>> pageResult = salesPlanReportRepository.pageQuery(pageQueryRequest);
        if (null != pageResult && pageResult.getTotal() > 0) {
            return Result.success(pageResult.getContent().get(0));
        }
        return Result.success(null) ;
    }

    /**
     * 查询前序提报单集审批状态
     * 前序提报单是否都审批通过
     *
     * @param request
     * @return
     */
    @Override
    @FacadeInvoker
    public Result<Boolean> queryPreSalesPlanReportAuditStatus(SalesPlanReportRequest request) {
        // 构建提报维度
        // 用户组织不是销售部门、销售渠道、分子公司则直接不显示按钮
        Integer userOrgType = request.getRelationOrganizationType();
        if (!OrganizationTypeEnum.SALES_DEPARTMENT.getCode().equals(userOrgType)
            && !OrganizationTypeEnum.SALES_CHANNEL.getCode().equals(userOrgType)
            && !OrganizationTypeEnum.COMPANY.getCode().equals(userOrgType)){
            log.info("SalesPlanReportQueryServiceImpl_fetchPreReportAuditStatus_result,用户组织不是销售部门、销售渠道、分子公司false");
            return Result.success(false);
        }

        boolean b = fetchPreReportAuditStatus(request);
        return Result.success(b);
    }

    /**
     * 查询提报单对应的审批记录
     *
     * @param request
     * @return
     */
    @Override
    @FacadeInvoker
    public Result<List<SalesPlanAuditRecordResponse>> querySalesPlanAuditRecordList(SalesPlanReportRequest request) {
        if (null == request || StringUtils.isBlank(request.getReportOrderId())) {
            return Result.success(Lists.newArrayList());
        }
        request.setReportOrderIdList(Lists.newArrayList(request.getReportOrderId()));
        // 获取提报单下所有的审批单
        List<SalesPlanAuditSDO> salesPlanAuditSDOList = querySalesPlanAuditList(request);
        if (CollectionUtils.isEmpty(salesPlanAuditSDOList)) {
            return Result.success(Lists.newArrayList());
        }
        // 获取所有的审批任务
        List<String> auditIdList = salesPlanAuditSDOList.stream().map(SalesPlanAuditSDO::getId).collect(Collectors.toList());
        List<SalesPlanAuditTaskSDO> salesPlanAuditTaskSDOList = querySalesPlanAuditTaskList(auditIdList);
        if (CollectionUtils.isEmpty(salesPlanAuditTaskSDOList)) {
            return Result.success(Lists.newArrayList());
        }
        return Result.success(refreshSalesPlanAuditRecord(salesPlanAuditSDOList, salesPlanAuditTaskSDOList));
    }

    /**
     * 查询当前操作人对应的提报单是否有审批权限
     *
     * @param request
     * @return
     */
    @Override
    @FacadeInvoker
    public Result<Boolean> verifyAuditPermission(SalesPlanReportRequest request) {
        // 参数检查
        if (!checkParam(request)) {
            return Result.success(false);
        }
        // 查询审批单
        SalesPlanReportSDO salesPlanReportSDO = fetchSalesPlanReportSDO(request.getReportOrderId());
        if (null == salesPlanReportSDO) {
            return Result.success(false);
        }
        if (SalesPlanReportAuditStatusEnum.UNDER_REVIEW.getCode() != salesPlanReportSDO.getAuditStatus()) {
            return Result.success(false);
        }
        // 校验审批人
        if (null == salesPlanReportSDO.getFeatures()) {
            return Result.success(false);
        }
        JSONObject jsonObject = JSONObject.parseObject(salesPlanReportSDO.getFeatures());
        if (StringUtils.isBlank(jsonObject.getString(FeaturesKeyEnum.TASK_CODE.getName()))) {
            return Result.success(false);
        }
        SalesPlanAuditTaskSDO salesPlanAuditTaskSDO = fetchSalesPlanAuditTaskSDO(jsonObject.getString(FeaturesKeyEnum.TASK_CODE.getName()));
        if (null == salesPlanAuditTaskSDO) {
            return Result.success(false);
        }
        if (null != salesPlanAuditTaskSDO.getAssignees() && salesPlanAuditTaskSDO.getAssignees().lastIndexOf(request.getOperatorId()) > -1) {
            return Result.success(true);
        }
        return Result.success(false);
    }

    /**
     * 批量验证审批权限
     * Map<String, Boolean>  key是提报单id，value是是否有审核权限
     *
     * @param request
     * @return
     */
    @Override
    public Result<Map<String, Boolean>> batchVerifyAuditPermission(SalesPlanReportRequest request) {
        // 参数校验
        if (!checkBatchVerifyAuditPermissionParam(request)) {
            return Result.success(Maps.newHashMap());
        }
        List<SalesPlanReportSDO> salesPlanReportSDOList = batchFetchSalesPlanReportSDO(request);
        if (CollectionUtils.isEmpty(salesPlanReportSDOList)) {
            return Result.success(Maps.newHashMap());
        }
        List<String> taskCodeList = Lists.newArrayList();
        Map<String, String> reportRelationMap = Maps.newHashMap();
        salesPlanReportSDOList.forEach(salesPlanReportSDO -> {
            if (SalesPlanReportAuditStatusEnum.UNDER_REVIEW.getCode() != salesPlanReportSDO.getAuditStatus()) {
                return;
            }
            // 校验审批人
            if (null == salesPlanReportSDO.getFeatures()) {
                return;
            }
            JSONObject jsonObject = JSONObject.parseObject(salesPlanReportSDO.getFeatures());
            String taskCode = jsonObject.getString(FeaturesKeyEnum.TASK_CODE.getName());
            if (StringUtils.isBlank(taskCode)) {
                return;
            }
            taskCodeList.add(taskCode);
            reportRelationMap.put(taskCode, salesPlanReportSDO.getId());
        });
        List<SalesPlanAuditTaskSDO> planAuditTaskSDOList = batchFetchSalesPlanAuditTaskSDO(taskCodeList);
        if (CollectionUtils.isEmpty(planAuditTaskSDOList)) {
            return Result.success(Maps.newHashMap());
        }
        Map<String , Boolean> auditMap = Maps.newHashMap();
        planAuditTaskSDOList.forEach(taskSDO -> {
            if (null == taskSDO.getAssignees() || taskSDO.getAssignees().lastIndexOf(request.getOperatorId()) < 0) {
                return;
            }
            if (null != reportRelationMap.get(taskSDO.getTaskCode())) {
                auditMap.put(reportRelationMap.get(taskSDO.getTaskCode()), true);
            }
        });
        return Result.success(auditMap);
    }

    @Override
    public Result<List<SalesPlanAuditRecordResponse>> querySalesPlanAuditRecordListV2(SalesPlanReportPageQueryRequest request) {
        log.error("SalesPlanReportQueryService.querySalesPlanAuditRecordListV2.request={}", JSONObject.toJSONString(request));
        if (null == request || StringUtils.isBlank(request.getModelId())) {
            return Result.success(Lists.newArrayList());
        }
        // 获取月度计划下所有的提报单
        SalesPlanReportLoadListRequest listRequest = new SalesPlanReportLoadListRequest();
        listRequest.setModelId(Long.valueOf(request.getModelId()));
        Result<List<SalesPlanReport>> listResult = salesPlanReportService.loadSalesPlanReportList(listRequest);
        log.error("SalesPlanReportQueryService.querySalesPlanAuditRecordListV2.listResult={}", JSONObject.toJSONString(listResult));
        if (CollectionUtils.isEmpty(listResult.getResult())) {
            return Result.success(Lists.newArrayList());
        }
        List<String> reportOrderIdList = listResult.getResult().stream().map(SalesPlanReport::getId).map(String::valueOf).collect(Collectors.toList());
        //
        Map</*EmployeeId*/String, /*BizType*/Integer> bizTypeMap = listResult.getResult().stream().collect(Collectors.toMap(SalesPlanReport::getReportEmployeeId, SalesPlanReport::getBizType));
        // 获取月度计划下所有的审批单
        SalesPlanReportRequest salesPlanReportRequest = new SalesPlanReportRequest();
        salesPlanReportRequest.setReportOrderIdList(reportOrderIdList);
        List<SalesPlanAuditSDO> salesPlanAuditSDOList = querySalesPlanAuditList(salesPlanReportRequest);
        log.error("SalesPlanReportQueryService.querySalesPlanAuditRecordListV2.salesPlanAuditSDOList={}", JSONObject.toJSONString(salesPlanAuditSDOList));
        if (CollectionUtils.isEmpty(salesPlanAuditSDOList)) {
            return Result.success(Lists.newArrayList());
        }
        // 获取所有的审批任务
        List<String> auditIdList = salesPlanAuditSDOList.stream().map(SalesPlanAuditSDO::getId).collect(Collectors.toList());
        List<SalesPlanAuditTaskSDO> salesPlanAuditTaskSDOList = querySalesPlanAuditTaskList(auditIdList);
        log.error("SalesPlanReportQueryService.querySalesPlanAuditRecordListV2.salesPlanAuditTaskSDOList={}", JSONObject.toJSONString(salesPlanAuditTaskSDOList));
        if (CollectionUtils.isEmpty(salesPlanAuditTaskSDOList)) {
            return Result.success(Lists.newArrayList());
        }
//        salesPlanAuditTaskSDOList = salesPlanAuditTaskSDOList.stream().filter(taskSDO -> checkTaskSDO(taskSDO, bizTypeMap)).collect(Collectors.toList());
//        log.error("SalesPlanReportQueryService.querySalesPlanAuditRecordListV2.filterTaskSDOList={}", JSONObject.toJSONString(salesPlanAuditTaskSDOList));
        return Result.success(refreshSalesPlanAuditRecord(salesPlanAuditSDOList, salesPlanAuditTaskSDOList, bizTypeMap));
    }

    @Override
    public Result<Boolean> verifyRevokePermission(SalesPlanReportRequest request) {
        log.error("verifyRevokePermission.request={}", JSONObject.toJSONString(request));
        // 参数检查
        if (!checkRevokePermissionParam(request)) {
            return Result.success(false);
        }
        // 查询当前登录人的审批单
        QuerySalesPlanReportRequest querySalesPlanReportRequest = new QuerySalesPlanReportRequest();
        querySalesPlanReportRequest.setModelId(request.getModelId());
        querySalesPlanReportRequest.setModel(request.getModel());
        if (request.getIsSales()) {
            querySalesPlanReportRequest.setBizId(request.getOperatorId());
        } else {
            querySalesPlanReportRequest.setBizId(request.getRelationOrganizationId());
        }
        log.error("verifyRevokePermission.querySalesPlanReportRequest={}", JSONObject.toJSONString(querySalesPlanReportRequest));
        List<SalesPlanReportSDO> reportList = salesPlanReportRepository.querySalesPlanReportList(querySalesPlanReportRequest);
        log.error("verifyRevokePermission.reportList={}", JSONObject.toJSONString(reportList));
        if (CollectionUtils.isEmpty(reportList)) {
            return Result.success(false);
        }
        List<SalesPlanReportSDO> reviewList = reportList.stream().filter(x -> SalesPlanReportAuditStatusEnum.UNDER_REVIEW.getCode().equals(x.getAuditStatus())).collect(Collectors.toList());
        log.error("verifyRevokePermission.reviewList={}", JSONObject.toJSONString(reviewList));
        if (CollectionUtils.isEmpty(reviewList)) {
            return Result.success(false);
        }
        // 业务员特判
        if (request.getIsSales()) {
            return Result.success(reviewList.stream().anyMatch(x -> request.getOperatorId().equals(x.getBizId())));
        }
        // 校验当前登录人的组织
        SalesStatBizTypeEnum bizTypeEnum = SalesStatBizTypeEnum.getByOrganizationType(request.getRelationOrganizationType());
        log.error("verifyRevokePermission.bizTypeEnum={}", JSONObject.toJSONString(bizTypeEnum));
        if (null == bizTypeEnum) {
            return Result.success(false);
        }
        // 校验当前登录人的审批节点
        Boolean bool = checkAuditSetting(request);
        return Result.success(bool && reviewList.stream().anyMatch(x -> bizTypeEnum.getBizType().equals(x.getBizType())));
//        return Result.success(false);
    }

    private List<String> getRoleCodes(String roleCode) {
        log.error("SalesPlanReportQueryService.getRoleCodes.roleCode={}", roleCode);
        List<String> roleCodes = Lists.newArrayList();
        try {
            String[] roleList = roleCode.replace("[", "").replace("]", "")
                    .replace("\"","").split(",");
            for (String s : roleList) {
                s = s.trim();
                roleCodes.add(s);
            }
            log.error("SalesPlanReportQueryService.getRoleCodes.roleCodes={}", roleCodes);
        } catch (Exception e) {
            log.error("SalesPlanReportQueryService.getRoleCodes.转换角色失败={}", e);
            throw new FacadeException("角色信息转换失败");
        }
        return roleCodes;
    }

    private Boolean checkAuditSetting(SalesPlanReportRequest request) {
        List<AuditSetting> auditSettings = getAuditSetting(request.getRelationOrganizationType(), request.getRelationOrganizationId(), request.getModel());
        List<String> roleCodes = getRoleCodes(request.getRoleCodeString());
        Map<String, String> roleSDOMap = getRoleSDOMap();
        for (AuditSetting auditSetting : auditSettings) {
            Map<String, List<AuditSettingDetail>> map = getAuditSettingDetailMap(auditSetting, roleCodes, request.getRelationOrganizationType(), roleSDOMap);
            if (MapUtils.isEmpty(map)) {
                continue;
            }
            AuditSettingDetail currentAudit = map.get("currentAudit").get(0);
            AuditSettingDetail lastAudit = map.get("lastAudit").get(0);
            if (Objects.isNull(currentAudit)) {
                log.error("SalesPlanReportQueryService.checkReportSetting.当前提报人未配置审批节点：{}", JSONObject.toJSONString(auditSetting));
                continue;
            }
            // 最后一个审批节点的角色不能提交审批和撤回审批
            if (currentAudit.getId().equals(lastAudit.getId())) {
                log.error("SalesPlanReportQueryService.checkReportSetting.当前提报人处于最后一个审批节点：{}", JSONObject.toJSONString(auditSetting));
                continue;
            }
            log.error("SalesPlanReportQueryService.checkReportSetting.满足条件的审批节点：{}", JSONObject.toJSONString(auditSetting));
            return true;
        }
        log.error("SalesPlanReportQueryService.checkReportSetting.没有满足条件的审批节点");
        return false;
    }

    private Map<String, List<AuditSettingDetail>> getAuditSettingDetailMap(AuditSetting auditSetting, List<String> roleCodes, Integer OrganizationType, Map</*code*/String, /*id*/String> roleSDOMap) {
        List<AuditSettingDetail> auditDetails = obtainAuditSettingDetail(auditSetting);
        log.error("SalesPlanReportQueryService.getAuditSettingDetail={}", JSONObject.toJSONString(auditDetails));
        if (org.apache.commons.collections.CollectionUtils.isEmpty(auditDetails)) {
            log.error("SalesPlanReportQueryService.getAuditSettingDetail当前审批主单id={}, settingDetail={}", auditSetting.getId(),
                    JSONObject.toJSONString(auditSetting));
            throw new FacadeException(ErrorMessage.code("OTS-02-002-01-16-025"));
        }
        Map<String, List<AuditSettingDetail>> map = new HashMap<>();
        Map<String, AuditSettingDetail> detailMap = Maps.newHashMap();
        // 记录最后一个审批节点
        AuditSettingDetail lastAudit = null;
        for (AuditSettingDetail auditDetail : auditDetails) {
            String organizationType = auditDetail.getOrganizationType();
            String roleId = auditDetail.getRoleId();
            if (Objects.isNull(detailMap.get(organizationType + roleId))) {
                detailMap.put(organizationType + roleId, auditDetail);
            }
            if (null == lastAudit || auditDetail.getAuditSequence() > lastAudit.getAuditSequence()) {
                lastAudit = auditDetail;
            }
        }
        // 记录当前审批节点
        AuditSettingDetail currentAudit = null;
        for (String roleCode : roleCodes) {
            AuditSettingDetail auditSettingDetail = detailMap.get(OrganizationType + roleSDOMap.get(roleCode));
            if (!Objects.isNull(auditSettingDetail)) {
                currentAudit = auditSettingDetail;
            }
        }
        if (Objects.isNull(currentAudit)) {
            return map;
        }
        map.put("currentAudit", Lists.newArrayList(currentAudit));
        map.put("lastAudit", Lists.newArrayList(lastAudit));
        //记录当前审批节点的下一个节点
        AuditSettingDetail firstAudit = currentAudit;
        List<AuditSettingDetail> list = auditDetails.stream().filter(detail -> {
            return detail.getAuditSequence() == firstAudit.getAuditSequence() + 1;
        }).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(list)) {
            log.error("SalesPlanReportQueryService.getAuditSettingDetail.当前审批人无后续节点");
            return map;
        }
        AuditSettingDetail nextAudit = list.get(0);
        // 记录后续审批节点(不包含当前和下一个节点)
        List<AuditSettingDetail> subsequentAudit = auditDetails.stream().filter(detail -> !Objects.isNull(detail)
                && nextAudit.getAuditSequence() < detail.getAuditSequence()).collect(Collectors.toList());
        map.put("nextAudit", Lists.newArrayList(nextAudit));
        map.put("subsequentAudit", Lists.newArrayList(subsequentAudit));
        return map;
    }

    private List<AuditSettingDetail> obtainAuditSettingDetail(AuditSetting request) {
        Result<List<AuditSettingDetail>> result = auditSettingDetailService.loadList(buildAuditSettingDetailRequest(request));
        if (!result.isSuccess() || org.apache.commons.collections.CollectionUtils.isEmpty(result.getResult())) {
            return Lists.newArrayList();
        }
        return result.getResult();
    }

    private AuditSettingDetailLoadListRequest buildAuditSettingDetailRequest(AuditSetting request) {
        AuditSettingDetailLoadListRequest detailRequest = new AuditSettingDetailLoadListRequest();
        detailRequest.setAuditSettingId(request.getId());
        detailRequest.setStatus(AuditSettingStatusEnum.ENABLE.getType());
        return detailRequest;
    }

    private Map</*code*/String, /*id*/String> getRoleSDOMap() {
        Map<String, String> roleSDOMap = new HashMap<>();
        Result<List<RoleSDO>> result = bcOrderService.getAllRoles(GetAllRolesRequest.builder().belongOrganizationId("1").build());
        if (!result.isSuccess() || org.apache.commons.collections4.CollectionUtils.isEmpty(result.getResult())) {
            log.info("查询角色信息失败AuditSettingDetailService.convertResponseList");
        } else {
            roleSDOMap = result.getResult().stream().collect(Collectors.toMap(RoleSDO::getCode, RoleSDO::getId, (a, b) -> a));
        }
        return roleSDOMap;
    }

    private List<AuditSetting> getAuditSetting(Integer organizationType, String organizationId, Integer model) {
        SalesPlanReportRequest salesPlanRequest = new SalesPlanReportRequest();
        salesPlanRequest.setModel(model);
        // 当前为销售渠道，或销售单元可直接获取对应审批配置
        if (OrganizationTypeEnum.SALES_CHANNEL.getCode().equals(organizationType)) {
            salesPlanRequest.setRelationOrganizationId(organizationId);
            salesPlanRequest.setRelationOrganizationType(OrganizationTypeEnum.SALES_CHANNEL.getCode());
        } else if (OrganizationTypeEnum.COMPANY.getCode().equals(organizationType)) {
            salesPlanRequest.setRelationOrganizationId(organizationId);
            salesPlanRequest.setRelationOrganizationType(OrganizationTypeEnum.COMPANY.getCode());
        } else if (OrganizationTypeEnum.SALES_DEPARTMENT.getCode().equals(organizationType)) {
            // 向上反查对应组织id
            com.epoch.app.crplatformenhance.sdo.OrganizationSDO organizationSDO = obtainUpOrganization(organizationId, OrganizationTypeEnum.SALES_CHANNEL.getCode());
            salesPlanRequest.setRelationOrganizationId(organizationSDO.getId());
            salesPlanRequest.setRelationOrganizationType(OrganizationTypeEnum.SALES_CHANNEL.getCode());
        } else if (OrganizationTypeEnum.SALES_ORGANIZATION.getCode().equals(organizationType)) {
            // 向上反查对应组织id
            com.epoch.app.crplatformenhance.sdo.OrganizationSDO organizationSDO = obtainUpOrganization(organizationId, OrganizationTypeEnum.COMPANY.getCode());
            salesPlanRequest.setRelationOrganizationId(organizationSDO.getId());
            salesPlanRequest.setRelationOrganizationType(OrganizationTypeEnum.COMPANY.getCode());
        } else  {
            throw new FacadeException(ErrorMessage.code("OTS-02-002-01-16-024"));
        }
        log.info("SalesPlanReportQueryService.obtainAuditSetting.request={}", JSONObject.toJSONString(salesPlanRequest));
        List<AuditSetting> auditSettings = obtainAuditSetting(salesPlanRequest);
        if (org.apache.commons.collections.CollectionUtils.isEmpty(auditSettings)) {
            throw new FacadeException(ErrorMessage.code("OTS-02-002-01-16-023"));
        }
        log.info("SalesPlanReportQueryService.obtainAuditSetting.auditSettings={}", JSONObject.toJSONString(auditSettings));
        return auditSettings;
    }

    private List<AuditSetting> obtainAuditSetting(SalesPlanReportRequest request) {
        // 获取审批配置主单、可能有多个
        Result<List<AuditSetting>> result = auditSettingService.loadList(buildAuditSettingRequest(request));
        if (!result.isSuccess() || org.apache.commons.collections.CollectionUtils.isEmpty(result.getResult())) {
            return Lists.newArrayList();
        }
        return result.getResult();
    }

    /**
     * 过滤驳回的审批任务
     * @param taskSDO
     * @param bizTypeMap
     * @return
     */
    private Boolean checkTaskSDO (SalesPlanAuditTaskSDO taskSDO, Map</*EmployeeId*/String, /*BizType*/Integer> bizTypeMap) {
        // 可审批人id集合
        String assignees = taskSDO.getAssignees();
        if (StringUtils.isEmpty(assignees)) {
            return false;
        }
        // 发起人组织纬度
        Integer initiatorBizType = bizTypeMap.get(taskSDO.getAuditInitiatorId());
        // 审批人组织纬度
        Integer auditBizType = bizTypeMap.get(taskSDO.getPrincipal());
        // 发起人无提报单，则发起人就是上级
        if (null == initiatorBizType) {
            return false;
        }
        // 发起人为业务员，可以展示
        if (initiatorBizType.equals(SalesStatBizTypeEnum.SALESMAN.getBizType())) {
            return true;
        }
        // 发起人组织纬度大于审批人组织纬度，则发起人就是上级
        if (null != auditBizType && initiatorBizType.compareTo(auditBizType) > 0) {
            return false;
        }
        // 任务未执行时，比较发起人和可审批人的组织纬度
        if (null == auditBizType) {
            String[] employeeIds = assignees.split(",");
            for (String employeeId : employeeIds) {
                if (null != bizTypeMap.get(employeeId)) {
                    auditBizType = bizTypeMap.get(employeeId);
                    break;
                }
            }
        }
        // 可审批人也不在提报单中，则发起人为下级，可以展示
        if (null == auditBizType) {
            return true;
        }
        return initiatorBizType.compareTo(auditBizType) <= 0;
    }

    private List<SalesPlanReportSDO> batchFetchSalesPlanReportSDO(SalesPlanReportRequest request) {
        SalesPlanReportPageQueryRequest pageQueryRequest = new SalesPlanReportPageQueryRequest();
        pageQueryRequest.setStart(0);
        pageQueryRequest.setLimit(200);
        pageQueryRequest.setReportIdList(request.getReportOrderIdList().stream().map(Long::parseLong).collect(Collectors.toList()));
        PageResult<List<SalesPlanReportSDO>> pageResult = salesPlanReportRepository.pageQuery(pageQueryRequest);
        if (null == pageResult || pageResult.getTotal() < 1) {
            return null;
        }
        return pageResult.getContent();
    }

    private List<SalesPlanAuditTaskSDO> batchFetchSalesPlanAuditTaskSDO(List<String> taskCodeList) {
        if (CollectionUtils.isEmpty(taskCodeList)) {
            return null;
        }
        SalesPlanAuditTaskQueryRequest request = new SalesPlanAuditTaskQueryRequest();
        request.setTaskCodeList(taskCodeList);
        request.setStart(0);
        request.setLimit(200);
        PageResult<List<SalesPlanAuditTaskSDO>> pageResult = salesPlanAuditTaskRepository.pageQuery(request);
        if (null == pageResult || pageResult.getTotal() < 1) {
            return null;
        }
        return pageResult.getContent();
    }

    private boolean checkBatchVerifyAuditPermissionParam(SalesPlanReportRequest request) {
        if (null == request) {
            return false;
        }
        if (CollectionUtils.isEmpty(request.getReportOrderIdList())) {
            return false;
        }
        return !StringUtils.isBlank(request.getOperatorId());
    }

    private SalesPlanAuditTaskSDO fetchSalesPlanAuditTaskSDO(String taskCode) {
        SalesPlanAuditTaskQueryRequest request = new SalesPlanAuditTaskQueryRequest();
        request.setTaskCode(taskCode);
        request.setStart(0);
        request.setLimit(1);
        PageResult<List<SalesPlanAuditTaskSDO>> pageResult = salesPlanAuditTaskRepository.pageQuery(request);
        if (null == pageResult || pageResult.getTotal() < 1) {
            return null;
        }
        return pageResult.getContent().get(0);
    }

    private SalesPlanReportSDO fetchSalesPlanReportSDO(String reportId) {
        QuerySalesPlanReportRequest request = new QuerySalesPlanReportRequest();
        request.setId(reportId);
        return salesPlanReportRepository.load(request);
    }

    private boolean checkParam(SalesPlanReportRequest request) {
        if (null == request) {
            return false;
        }
        if (StringUtils.isBlank(request.getReportOrderId())) {
            return false;
        }
        return !StringUtils.isBlank(request.getOperatorId());
    }

    private boolean checkRevokePermissionParam(SalesPlanReportRequest request) {
        if (null == request) {
            return false;
        }
        if (StringUtils.isBlank(request.getModelId()) || null == request.getModel() || StringUtils.isBlank(request.getRoleCodeString())) {
            return false;
        }
        return !StringUtils.isBlank(request.getOperatorId());
    }

    private List<SalesPlanAuditRecordResponse> refreshSalesPlanAuditRecord(List<SalesPlanAuditSDO> salesPlanAuditSDOList, List<SalesPlanAuditTaskSDO> salesPlanAuditTaskSDOList, Map</*EmployeeId*/String, /*BizType*/Integer> bizTypeMap) {
        Map<String, String> operateNameMap = fetchOperatorName(salesPlanAuditTaskSDOList);
        Map<String, SalesPlanAuditSDO> auditSDOMap = salesPlanAuditSDOList.stream().collect(Collectors.toMap(SalesPlanAuditSDO::getId, Function.identity()));
        List<SalesPlanAuditRecordResponse> salesPlanAuditRecordResponseList = Lists.newArrayList();
        salesPlanAuditTaskSDOList.forEach(taskSDO -> {
            salesPlanAuditRecordResponseList.addAll(refreshSalesPlanAuditRecordResponse(taskSDO, operateNameMap, auditSDOMap.get(taskSDO.getAuditOrderId()), bizTypeMap));
        });
        log.error("SalesPlanReportQueryService.querySalesPlanAuditRecordListV2.salesPlanAuditRecordResponseList={}", JSONObject.toJSONString(salesPlanAuditRecordResponseList));
        return salesPlanAuditRecordResponseList.stream().sorted(Comparator.comparing(SalesPlanAuditRecordResponse::getOperateTime).reversed()).collect(Collectors.toList());
    }

    private List<SalesPlanAuditRecordResponse> refreshSalesPlanAuditRecordResponse(SalesPlanAuditTaskSDO taskSDO, Map<String, String> operateNameMap, SalesPlanAuditSDO auditSDO, Map</*EmployeeId*/String, /*BizType*/Integer> bizTypeMap) {
        List<SalesPlanAuditRecordResponse> recordResponses = Lists.newArrayList();
        SalesPlanAuditRecordResponse response;
        // 发起人
        if (StringUtils.isNotBlank(taskSDO.getAuditInitiatorId()) && checkTaskSDO(taskSDO, bizTypeMap)) {
            response = new SalesPlanAuditRecordResponse();
            response.setOperatorName(operateNameMap.get(taskSDO.getAuditInitiatorId().replace(USER_PREFIX, "")));
            response.setOperateTime(taskSDO.getAuditStartTime());
            response.setAuditOperateType(AuditOperateTypeEnum.START_UP.getType());
            response.setAuditOperateDesc(AuditOperateTypeEnum.START_UP.getDesc());
            recordResponses.add(response);
        }
        // 处理人
        if (StringUtils.isNotBlank(taskSDO.getPrincipal())) {
            response = new SalesPlanAuditRecordResponse();
            response.setOperatorName(operateNameMap.get(taskSDO.getPrincipal().replace(USER_PREFIX, "")));
            response.setOperateTime(taskSDO.getAuditFinishTime());
            if (SalePlanAuditStatusEnum.FINISHED.getCode().equals(taskSDO.getStatus())) {
                response.setAuditOperateType(AuditOperateTypeEnum.APPROVE.getType());
                response.setAuditOperateDesc(AuditOperateTypeEnum.APPROVE.getDesc());
            } else if (SalePlanAuditStatusEnum.REJECT.getCode().equals(taskSDO.getStatus())){
                response.setAuditOperateType(AuditOperateTypeEnum.REJECT.getType());
                response.setAuditOperateDesc(AuditOperateTypeEnum.REJECT.getDesc());
                response.setComment(auditSDO.getAuditReason());
            } else if (SalePlanAuditStatusEnum.REVOKE.getCode().equals(taskSDO.getStatus())) {
                response.setAuditOperateType(AuditOperateTypeEnum.REVOKE.getType());
                response.setAuditOperateDesc(AuditOperateTypeEnum.REVOKE.getDesc());
                response.setComment(auditSDO.getAuditReason());
            }
            recordResponses.add(response);
        }
        return recordResponses;
    }

    private List<SalesPlanAuditRecordResponse> refreshSalesPlanAuditRecord(List<SalesPlanAuditSDO> salesPlanAuditSDOList, List<SalesPlanAuditTaskSDO> salesPlanAuditTaskSDOList) {
        Map<String, String> operateNameMap = fetchOperatorName(salesPlanAuditTaskSDOList);
        Map<String, SalesPlanAuditSDO> auditSDOMap = salesPlanAuditSDOList.stream().collect(Collectors.toMap(SalesPlanAuditSDO::getId, Function.identity()));
        List<SalesPlanAuditRecordResponse> salesPlanAuditRecordResponseList = Lists.newArrayList();
        salesPlanAuditTaskSDOList.forEach(taskSDO -> {
            salesPlanAuditRecordResponseList.addAll(refreshSalesPlanAuditRecordResponse(taskSDO, operateNameMap, auditSDOMap.get(taskSDO.getAuditOrderId())));
        });
        log.error("SalesPlanReportQueryService.querySalesPlanAuditRecordListV2.salesPlanAuditRecordResponseList={}", JSONObject.toJSONString(salesPlanAuditRecordResponseList));
        return salesPlanAuditRecordResponseList.stream().sorted(Comparator.comparing(SalesPlanAuditRecordResponse::getOperateTime).reversed()).collect(Collectors.toList());
    }

    private List<SalesPlanAuditRecordResponse> refreshSalesPlanAuditRecordResponse(SalesPlanAuditTaskSDO taskSDO, Map<String, String> operateNameMap, SalesPlanAuditSDO auditSDO) {
        List<SalesPlanAuditRecordResponse> recordResponses = Lists.newArrayList();
        SalesPlanAuditRecordResponse response;
        // 发起人
        if (StringUtils.isNotBlank(taskSDO.getAuditInitiatorId())) {
            response = new SalesPlanAuditRecordResponse();
            response.setOperatorName(operateNameMap.get(taskSDO.getAuditInitiatorId().replace(USER_PREFIX, "")));
            response.setOperateTime(taskSDO.getAuditStartTime());
            response.setAuditOperateType(AuditOperateTypeEnum.START_UP.getType());
            response.setAuditOperateDesc(AuditOperateTypeEnum.START_UP.getDesc());
            recordResponses.add(response);
        }
        // 处理人
        if (StringUtils.isNotBlank(taskSDO.getPrincipal())) {
            response = new SalesPlanAuditRecordResponse();
            response.setOperatorName(operateNameMap.get(taskSDO.getPrincipal().replace(USER_PREFIX, "")));
            response.setOperateTime(taskSDO.getAuditFinishTime());
            if (SalePlanAuditStatusEnum.FINISHED.getCode().equals(taskSDO.getStatus())) {
                response.setAuditOperateType(AuditOperateTypeEnum.APPROVE.getType());
                response.setAuditOperateDesc(AuditOperateTypeEnum.APPROVE.getDesc());
            } else if (SalePlanAuditStatusEnum.REJECT.getCode().equals(taskSDO.getStatus())){
                response.setAuditOperateType(AuditOperateTypeEnum.REJECT.getType());
                response.setAuditOperateDesc(AuditOperateTypeEnum.REJECT.getDesc());
                response.setComment(auditSDO.getAuditReason());
            } else if (SalePlanAuditStatusEnum.REVOKE.getCode().equals(taskSDO.getStatus())) {
                response.setAuditOperateType(AuditOperateTypeEnum.REVOKE.getType());
                response.setAuditOperateDesc(AuditOperateTypeEnum.REVOKE.getDesc());
                response.setComment(auditSDO.getAuditReason());
            }
            recordResponses.add(response);
        }
        return recordResponses;
    }

    private Map<String, String> fetchOperatorName(List<SalesPlanAuditTaskSDO> salesPlanAuditTaskSDOList) {
        List<String> userIdList = Lists.newArrayList();
        salesPlanAuditTaskSDOList.forEach(salesPlanAuditTaskSDO -> {
            if (StringUtils.isNotBlank(salesPlanAuditTaskSDO.getAuditInitiatorId())) {
                userIdList.add(salesPlanAuditTaskSDO.getAuditInitiatorId().replace(USER_PREFIX, ""));
            }
            if (StringUtils.isNotBlank(salesPlanAuditTaskSDO.getPrincipal())) {
                userIdList.add(salesPlanAuditTaskSDO.getPrincipal().replace(USER_PREFIX, ""));
            }
        });
        List<EmployeeSDO> employeeSDOList = platformEnhanceRepository.getEmployeeList(userIdList);
        if (CollectionUtils.isEmpty(employeeSDOList)) {
            return Maps.newHashMap();
        }
        return employeeSDOList.stream().collect(Collectors.toMap(EmployeeSDO::getId, EmployeeSDO::getName));
    }

    private List<SalesPlanAuditTaskSDO> querySalesPlanAuditTaskList(List<String> auditOrderIdList) {
        SalesPlanAuditTaskQueryRequest taskQueryRequest = new SalesPlanAuditTaskQueryRequest();
        taskQueryRequest.setAuditOrderIdList(auditOrderIdList);
        taskQueryRequest.setLimit(100);
        taskQueryRequest.setStart(0);
        PageResult<List<SalesPlanAuditTaskSDO>> pageResult = salesPlanAuditTaskRepository.pageQuery(taskQueryRequest);
        if (null == pageResult || pageResult.getTotal() < 1) {
            return null;
        }
        return pageResult.getContent();
    }

    private List<SalesPlanAuditSDO> querySalesPlanAuditList(SalesPlanReportRequest request) {
        QuerySalesPlanAuditRequest auditRequest = new QuerySalesPlanAuditRequest();
        auditRequest.setReportOrderIdList(request.getReportOrderIdList());
        return salesPlanAuditRepository.querySalesPlanAuditList(auditRequest);
    }

    private SalesPlanReportPageQueryRequest convertSalesPlanReportPageQueryRequest(SalesPlanReportQueryRequest source) {
        if (null == source) {
            return null;
        }
        SalesPlanReportPageQueryRequest target = new SalesPlanReportPageQueryRequest();
        target.setBizId(source.getBizId());
        target.setBizType(source.getBizType());
        target.setModelId(source.getModelId());
        target.setModelType(source.getModelType());
        target.setReportEmployeeId(source.getOperatorId());
        return target;
    }

    private boolean fetchPreReportAuditStatus(SalesPlanReportRequest request) {
        QuerySalesPlanReportRequest querySalesPlanReportRequest = new QuerySalesPlanReportRequest();
        querySalesPlanReportRequest.setModelId(request.getModelId());
        querySalesPlanReportRequest.setModel(request.getModel());
        if(request.getIsSales()){
            querySalesPlanReportRequest.setParentId(request.getOperatorId());
        }else{
            querySalesPlanReportRequest.setParentId(request.getRelationOrganizationId());
        }
        // 校验当前登录人的审批节点
        if (!checkAuditSetting(request)) {
            return false;
        }
        List<SalesPlanReportSDO> reportList = salesPlanReportRepository.querySalesPlanReportList(querySalesPlanReportRequest);
        log.info("SalesPlanReportQueryServiceImpl_fetchPreReportAuditStatus_querySalesPlanReportList_request={},response={}",JSONObject.toJSON(querySalesPlanReportRequest),JSONObject.toJSON(reportList));
        if (CollectionUtils.isNotEmpty(reportList)) {
            // 判断前序提报单只要包含已完成且不包含审批中和审批驳回
            boolean flag = reportList.stream().anyMatch(x -> SalesPlanReportAuditStatusEnum.APPROVED.getCode().equals(x.getAuditStatus()))
                    && reportList.stream().noneMatch(x -> SalesPlanReportAuditStatusEnum.UNDER_REVIEW.getCode().equals(x.getAuditStatus())
                    || SalesPlanReportAuditStatusEnum.REVIEW_REJECTED.getCode().equals(x.getAuditStatus()));
            log.info("SalesPlanReportQueryServiceImpl_fetchPreReportAuditStatus_result,审批单判断{}",flag);
            // 前序未审核完成, 不能提交审批
            return flag;
        }else{
            //判断提报人当前是否处于第一审批节点,处于第一个审批节点中,审批按钮显示
            // 提报新接口开关，开关打开执行新接口代码
            if (SALES_PLAN_REPORT_SWITCH.equals(BcOrderConstants.SALES_PLAN_REPORT_SWITCH())) {
                if(checkFirstNode(request)){
                    log.info("SalesPlanReportQueryServiceImpl_fetchPreReportAuditStatus_result,查询无审批单但提报人处于第一审批节点true");
                    return true;
                }
            }
            log.info("SalesPlanReportQueryServiceImpl_fetchPreReportAuditStatus_result,查询无审批单且提报人不处于第一审批节点false");
            return false;
        }
    }

    /**
     * 判断提报人当前是否处于第一审批节点
     * @return boolean
     */
    private boolean checkFirstNode(SalesPlanReportRequest request) {
        List<AuditSetting> settingList = getAuditConfiguration(request);
        if (CollectionUtils.isEmpty(settingList)) {
            return false;
        }
        Map<String, String> allRoleMap = getAllRoleMap();   //rode,id
        AuditSetting auditSetting = settingList.stream().filter(x -> {
            return getAuditSettingDetailTop(x, allRoleMap,request);
        }).findFirst().orElse(null);
        return Objects.nonNull(auditSetting);
    }

    /**
     * 判断提报人当前是否处于第一审批节点
     * @return boolean
     */
    private boolean getAuditSettingDetailTop(AuditSetting auditSetting, Map<String, String> allRoleMap, SalesPlanReportRequest salesPlanReportRequest) {
        //通过审批主单id获取审批配置子单信息
        AuditSettingDetailLoadListRequest detailRequest = new AuditSettingDetailLoadListRequest();
        detailRequest.setAuditSettingId(auditSetting.getId());
        detailRequest.setStatus(AuditSettingStatusEnum.ENABLE.getType());
        Result<List<AuditSettingDetail>> auditDetailResult = auditSettingDetailService.loadList(detailRequest);
        if (!auditDetailResult.isSuccess() || CollectionUtils.isEmpty(auditDetailResult.getResult())) {
            throw new FacadeException(ErrorMessage.code("OTS-02-002-01-16-025"));
        }
        Map<String, AuditSettingDetail> auditDetailMap = auditDetailResult.getResult().stream().collect(Collectors.toMap(x->x.getOrganizationType()+x.getRoleId(), Function.identity(),(v1,v2)->v1));

        Integer userOrgType = salesPlanReportRequest.getRelationOrganizationType();
        List<String> userRoleCodes = Nullable.stream(salesPlanReportRequest.getRoleCodes()).map(x->{return x.replaceAll("\"","").trim();}).collect(Collectors.toList());
        String roleCode = userRoleCodes.stream().filter(code -> {
            AuditSettingDetail auditSettingDetail = auditDetailMap.get(userOrgType + allRoleMap.get(code));
            if (!Objects.isNull(auditSettingDetail)) {
                return auditSettingDetail.getAuditSequence() == 1;
            }
            return false;
        }).findFirst().orElse(null);

        return StringUtils.isNotBlank(roleCode);
    }

    private Map<String, String> getAllRoleMap() {
        Map<String, String> roleSDOMap = new HashMap<>();
        Result<List<RoleSDO>> result = bcOrderService.getAllRoles(GetAllRolesRequest.builder().belongOrganizationId("1").build());
        if (!result.isSuccess() || CollectionUtils.isEmpty(result.getResult())) {
            log.info("查询角色信息失败AuditSettingDetailService.convertResponseList");
        } else {
            roleSDOMap = result.getResult().stream().collect(Collectors.toMap(RoleSDO::getCode, RoleSDO::getId, (a, b) -> a));
        }
        return roleSDOMap;
    }

    /**
     * 获取审批配置
     * @param request request
     */
    private List<AuditSetting> getAuditConfiguration(SalesPlanReportRequest request) {
        SalesPlanReportRequest salesPlanRequest = new SalesPlanReportRequest();
        BeanUtils.copyProperties(request, salesPlanRequest);
        // 当前为销售渠道，或销售单元可直接获取对应审批配置
        if (OrganizationTypeEnum.SALES_CHANNEL.getCode().equals(request.getRelationOrganizationType()) ||
                OrganizationTypeEnum.COMPANY.getCode().equals(request.getRelationOrganizationType())) {

        } else if (OrganizationTypeEnum.SALES_DEPARTMENT.getCode().equals(request.getRelationOrganizationType())) {
            // 向上反查对应组织id
            OrganizationSDO organizationSDO = obtainUpOrganization(request.getRelationOrganizationId(), OrganizationTypeEnum.SALES_CHANNEL.getCode());
            salesPlanRequest.setRelationOrganizationId(organizationSDO.getId());
            salesPlanRequest.setRelationOrganizationType(OrganizationTypeEnum.SALES_CHANNEL.getCode());
        } else if (OrganizationTypeEnum.SALES_ORGANIZATION.getCode().equals(request.getRelationOrganizationType())) {
            // 向上反查对应组织id
            OrganizationSDO organizationSDO = obtainUpOrganization(request.getRelationOrganizationId(), OrganizationTypeEnum.COMPANY.getCode());
            salesPlanRequest.setRelationOrganizationId(organizationSDO.getId());
            salesPlanRequest.setRelationOrganizationType(OrganizationTypeEnum.COMPANY.getCode());
        } else  {
            throw new FacadeException(ErrorMessage.code("OTS-02-002-01-16-024"));
        }
        // 获取审批配置主单、可能有多个
        AuditSettingLoadListRequest auditSettingLoadListRequest = buildAuditSettingRequest(salesPlanRequest);
        Result<List<AuditSetting>> result = auditSettingService.loadList(auditSettingLoadListRequest);
        log.info("SalesPlanReportQueryServiceImpl_fetchPreReportAuditStatus_getAuditSetting_request={}，response={}", JSONObject.toJSONString(auditSettingLoadListRequest), JSONObject.toJSONString(result));
        if (!result.isSuccess() || CollectionUtils.isEmpty(result.getResult())) {
            return Lists.newArrayList();
        }
        return result.getResult();
    }

    /**
     * 获取当前审批人的上级组织
     * @return
     */
    private OrganizationSDO obtainUpOrganization(String relationOrganizationId, Integer upOrganizationType) {
        OrganizationListQueryRequest topOrganizationListRequest = new OrganizationListQueryRequest();
        topOrganizationListRequest.setId(relationOrganizationId);
        topOrganizationListRequest.setType(upOrganizationType);
        // 获取当前组织向上回溯指定类型组织列表
        List<OrganizationSDO> organizationSDOList = platformEnhanceRepository.getTopOrganizationList(topOrganizationListRequest);
        if (CollectionUtils.isEmpty(organizationSDOList)) {
            throw new FacadeException(ErrorMessage.code("OTS-02-003-01-16-013"));
        }
        // 获取最后一个组织即可
        return organizationSDOList.get(organizationSDOList.size() - 1);
    }

    private AuditSettingLoadListRequest buildAuditSettingRequest(SalesPlanReportRequest request) {
        AuditSettingLoadListRequest auditSettingRequest = new AuditSettingLoadListRequest();
        auditSettingRequest.setStatus(AuditSettingStatusEnum.ENABLE.getType());
        if (SalesPlanModelEnum.PLAN_MODEL.getModel().equals(request.getModel())) {
            auditSettingRequest.setType(AuditSettingTypeEnum.SALES_PLAN_REPORT.getType());
        } else if (SalesPlanModelEnum.ADJUST_MODEL.getModel().equals(request.getModel())) {
            auditSettingRequest.setType(AuditSettingTypeEnum.SALES_PLAN_ADJUST.getType());
        }
        if (OrganizationTypeEnum.SALES_DEPARTMENT.getCode().equals(request.getRelationOrganizationType()) ||
                OrganizationTypeEnum.SALES_CHANNEL.getCode().equals(request.getRelationOrganizationType())) {
            auditSettingRequest.setOrgChannelCode(request.getRelationOrganizationId());
        } else if (OrganizationTypeEnum.SALES_ORGANIZATION.getCode().equals(request.getRelationOrganizationType()) ||
                OrganizationTypeEnum.COMPANY.getCode().equals(request.getRelationOrganizationType())) {
            auditSettingRequest.setOrgBusinessUnitCode(request.getRelationOrganizationId());
        }
        return auditSettingRequest;
    }
}
